import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import styles from "./Password.module.css";
import React, { useEffect, useState } from "react";
import {
  Button,
  Input,
  Popconfirm,
  Space,
  Table,
  TableColumnsType,
} from "antd";
import { passwordApi, Result } from "../../utils/backend/server";
import { toast } from "../../components/Toast/Toast";
import {
  KeywordType,
  PasswordPair,
  PasswordWithType,
} from "../../utils/domain/keyword";
import { PasswordModal } from "./PasswordModal/PasswordModal";
import { AxiosError, AxiosResponse } from "axios";

export type PasswordType = {
  id?: string | number;
  // url: string;
  memo: string;
  pair: PasswordWithType[];
};

export type fetchPasswordType = {
  pageNo: number;
  pageSize: number;
  search: string;
  id: PasswordType["id"];
};
const formatDate = (date: string, isShort = false) => {
  const cur = new Date(date);
  if (isShort) {
    return `${cur.getFullYear()}-${cur.getMonth() + 1}-${cur.getDate()}`;
  } else {
    return `${cur.getFullYear()}-${
      cur.getMonth() + 1
    }-${cur.getDate()} ${cur.getHours()}:${cur.getMinutes()}:${cur.getSeconds()}`;
  }
};
export default () => {
  const [list, setList] = useState<PasswordPair[]>([]);
  const [searchParams] = useSearchParams();
  const [total, setTotal] = useState(0);
  const [query, setQuery] = useState({
    id: 0,
    search: "",
    pageNo: 1,
    pageSize: 10,
  });
  const [modal, setModal] = useState<{
    visible: boolean;
    type: "add" | "edit";
    item: PasswordPair;
  }>({
    visible: false,
    type: "add",
    item: {} as PasswordPair,
  });
  const to = useNavigate();

  const refresh = async () => {
    const { data, code, total } = await passwordApi.fetchPasswords(query);
    setList(data);
    setTotal(total);
    if (code === 200) toast("refresh success");
  };
  useEffect(() => {
    (async () => {
      const id = searchParams.get("id");
      // if (!id) {
      //   toast("id is required");
      //   return;
      // }
      setQuery((e) => ({ ...e, id: Number(id) }));
      // await refresh();
      // console.log(id, "id");
    })();
  }, []);

  useEffect(() => {
    if (query.id === 0) return;
    refresh();
  }, [query]);
  const columns: TableColumnsType<PasswordPair> = [
    {
      title: "ID",
      dataIndex: "id",
    },
    {
      title: "Account",
      dataIndex: "account",
    },
    {
      title: "Password",
      dataIndex: "password",
      render: (text: string) => <span>******</span>,
    },
    {
      title: "memo",
      dataIndex: "memo",
      render: (text: string) => (
        <p className={styles.memo}>
          <span>{text}</span>
        </p>
      ),
    },
    {
      title: "createTime",
      dataIndex: "createTime",
      render: (text: string) => {
        return <div>{`${formatDate(text, false)}`}</div>;
      },
    },
    {
      title: "operation",
      dataIndex: "operation",
      fixed: "right",
      render: (text: string, record: PasswordPair) => (
        <Space>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setModal({
                visible: true,
                item: record,
                type: "edit",
              });
            }}
          >
            edit
          </Button>
          <Popconfirm
            title="Are you sure to delete this password?"
            okText="Yes"
            cancelText="No"
            onConfirm={async () => {
              // console.log("delete");
              const { msg, code } = await passwordApi.delPassword(record.id);
              toast(msg);
              if (code !== 200) return;
              refresh();
            }}
          >
            <Button type="primary" danger size="small">
              delete
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <div className={styles.container}>
      <Space className={styles.addBox}>
        {/* add search input */}
        <Input
          type="text"
          placeholder="search"
          value={query.search}
          onChange={(val) =>
            setQuery((e) => ({ ...e, search: val.target.value }))
          }
        />
        <Button
          type="primary"
          onClick={() => {
            setModal({
              visible: true,
              type: "add",
              item: {} as PasswordPair,
            });
          }}
        >
          Add
        </Button>
        <Button
          onClick={() => {
            refresh();
          }}
        >
          Refresh
        </Button>
        <Button
          onClick={() => {
            to(-1);
          }}
        >
          Back
        </Button>
      </Space>

      <Table<PasswordPair>
        bordered
        rowKey={"id"}
        columns={columns}
        dataSource={list}
        scroll={{ x: 1000 }}
        pagination={{
          pageSize: query.pageSize,
          current: query.pageNo,
          total,
          onChange: (pageNo) => {
            setQuery((e) => ({ ...e, pageNo }));
          },
        }}
      />
      <PasswordModal
        item={modal.item}
        visible={modal.visible}
        onFinish={async (form) => {
          console.log(form, "form");
          const id = Number(searchParams.get("id"));
          // if (id === null) return toast("id is required");
          try {
            const { msg, code } = await passwordApi[
              modal.type === "add" ? "insertPassword" : "updatePassword"
            ](id, form);
            toast(msg);
            if (code === 200) {
              setModal({
                visible: false,
                type: "add",
                item: {} as PasswordPair,
              });
              refresh();
            }
          } catch (err: any) {
            toast(err.data.msg);
          }
        }}
        cancel={() => {
          setModal({
            visible: false,
            type: "add",
            item: {} as PasswordPair,
          });
        }}
      />
    </div>
  );
};
